package com.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;

/**
 * 客户端
 * @author gxkj-042
 *
 */
public class Client implements Runnable{
	
	private AsynchronousSocketChannel asc;
	
	public Client() throws IOException {
		asc = AsynchronousSocketChannel.open();
	}
	
	public void connect(){
		asc.connect(new InetSocketAddress("127.0.0.1", 8765));
	}
	/**
	 * 写入数据
	 * @param request
	 */
	public void write(String request){
		try {
			asc.write(ByteBuffer.wrap(request.getBytes())).get();
			read();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 读取数据
	 */
	private void read() {
		ByteBuffer buf = ByteBuffer.allocate(1024);
		try {
			asc.read(buf).get();
			buf.flip();
			byte []respByte = new byte[buf.remaining()];
			buf.get(respByte);
			System.out.println("接收到服务器端响应："+new String(respByte,"utf-8").trim());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while (true) {
			
		}
	}
	public static void main(String[] args) throws IOException {
		Client c1 = new Client();
		c1.connect();
		
		Client c2 = new Client();
		c2.connect();
		
		Client c3 = new Client();
		c3.connect();
		
		c1.write("c1 aaa");
		c2.write("c2 bbbb");
		c3.write("c3 pppppppp");
	}
}
